const path = require("path");

const { promisify } = require("util");
const download = promisify(require("download-git-repo"));

const { vuePeo } = require("../config/repo-config");
const { commandSpawn } = require("../utils/terminal");

const { compile, writeToFile, createDirSync } = require("../utils/utils");

const createProjectAction = async (project, others) => {
  console.log("开始创建项目...");
  await download(vuePeo, project, { clone: false });
  console.log("开始下载依赖...");
  const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
  await commandSpawn(npmCommand, ["install"], { cwd: `./${project}` });
  console.log("依赖下载完毕...");
};

const addComponentAction = async (name, dest) => {
  const result = await compile("vue-component.ejs", {
    name,
    lowerName: name.toLowerCase(),
  });
  const writePath = path.resolve(dest, `./${name}.vue`);

  if (createDirSync(dest)) {
    await writeToFile(writePath, result);
    console.log(`组件创建成功：${writePath}`);
  }
};

const addPageAction = async (name, pathName) => {
  const lowerName = name.toLowerCase();

  const data = { name, lowerName };

  pathName = `${pathName}/${lowerName}/`;


  const PageContent = await compile("vue-component.ejs", data);
  const RouterContent = await compile("vue-router.js.ejs", data);
  const pagePath = path.resolve(pathName, `./${name}.vue`);
  const routerPath = path.resolve(pathName, `./router.js`);

  if (createDirSync(pathName)) {
    writeToFile(pagePath, PageContent);
    writeToFile(routerPath, RouterContent);
    console.log(`页面创建成功${pagePath}`);
  }
};

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAction,
};
